package com.atguigu.guli.service.ucenter.controller.api;

/**
 * @author: Mr.Wang
 * @date: 2021-06-14 21:28
 * @description:
 */

import com.atguigu.commonutils.ExceptionUtils;
import com.atguigu.commonutils.ResultCodeEnum;
import com.atguigu.guli.service.base.Exception.GuliException;
import com.atguigu.guli.service.ucenter.util.UcenterProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class ApiWxControler {
    @Autowired
    private UcenterProperties ucenterProperties;

    @GetMapping("/login")
    public String genQrConnect(HttpSession session){

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
        "?appid=%s" + //%s为占位符，下面需要进行填充
        "&redirect_uri=%s" +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=%s" +
        "#wechat_redirect";


        //对于redirect_uri需要进行处理，替换里面的特殊字符
        String redirecturi = "";
        try {
             redirecturi  = URLEncoder.encode(ucenterProperties.getRedirectUri(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.URL_ENCODE_ERROR);
        }

        //对于state进行处理，生成随机数，存入session中

        String state = UUID.randomUUID().toString();
        log.info("生成 state = " + state);
        session.setAttribute("wx_open_state", state);


        String qrcodeUrl = String.format(
                baseUrl,
                ucenterProperties.getAppId(),
                redirecturi,
                state
        );

        return "redirect:" + qrcodeUrl;
    }
}
